package com.wealth.wechat.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wealth.wechat.entity.WechatConfig;
import com.wealth.wechat.enums.ScopeEnum;
import com.wealth.wechat.service.WechatConfigService;
import com.wealth.wechat.util.CommonUtil;
import com.wealth.wechat.vo.UserInfo;

import iaas.utils.ResultObject;
import iaas.web.EmojiFilter;

/**
 * @author chan
 */
@Controller
@RequestMapping("/wechat")
public class WechatContrller {

	Logger logger = Logger.getLogger(WechatContrller.class);

	@Autowired
	private WechatConfigService wechatConfigService;
	
	/** 
	 * 测试例子
	 * 实际项目中自己根据情况，将代码粘贴到控制器
	 * 
	 * 如报名页面，
	 * 控制器复制  "跳转测试页面- 静默获取微信号"中的代码
	 * 页面复制      "snsapi_base.ftl"中的代码
	 */
	
	/** 跳转测试页面- 静默获取微信号 */
	@RequestMapping(value="/{corpid}/1",method = RequestMethod.GET)
	public String getOpenid(@PathVariable Long corpid,Model model,HttpServletRequest request) {
		WechatConfig config = wechatConfigService.getWechatConfigByCorpid(corpid);
		model.addAttribute("appid",(config!=null)?config.getWxappid():null);
		model.addAttribute("corpid", corpid);
		if(request.getParameter("openid")!=null){
			model.addAttribute("openid", request.getParameter("openid"));
		}
		return "wechat/1";
	}
	
	/** 跳转测试页面  - 网页授权获取个人信息 微信号 昵称 头像 */
	@RequestMapping(value="/{corpid}/2",method = RequestMethod.GET)
	public String getUserinfo(@PathVariable Long corpid,Model model,HttpServletRequest request) {
		try {
			WechatConfig config = wechatConfigService.getWechatConfigByCorpid(corpid);
			model.addAttribute("appid",(config!=null)?config.getWxappid():null);
			model.addAttribute("corpid", corpid);
			if(request.getParameter("openid")!=null){
				model.addAttribute("openid", request.getParameter("openid"));
				model.addAttribute("nickname", java.net.URLDecoder.decode(request.getParameter("nickname"),"UTF-8"));
				model.addAttribute("headimgurl", request.getParameter("headimgurl"));
				model.addAttribute("sex", request.getParameter("sex"));
			}
			return "wechat/2";
		}catch (Exception e) {
			logger.error("网页授权获取个人信息出错", e);
			return "system/500";
		}	
	}
	
	/** 跳转夹层  静默获取微信号 */
	@RequestMapping(value="/snsapi_base",method = RequestMethod.GET)
	public String snsapi_base(Model model,HttpServletRequest request){
		String requrl =request.getParameter("requrl");
		String corpid =request.getParameter("corpid");
		String appid =request.getParameter("appid");
		model.addAttribute("requrl", requrl);
		model.addAttribute("corpid", corpid);
		model.addAttribute("appid", appid);
		return "wechat/snsapi_base";
	}
	
	/** 跳转夹层  网页授权获取个人信息 微信号 昵称 头像 */
	@RequestMapping(value="/snsapi_userinfo",method = RequestMethod.GET)
	public String snsapi_userinfo(Model model,HttpServletRequest request){
		String requrl =request.getParameter("requrl");
		String corpid =request.getParameter("corpid");
		String appid =request.getParameter("appid");
		model.addAttribute("requrl", requrl);
		model.addAttribute("corpid", corpid);
		model.addAttribute("appid", appid);
		return "wechat/snsapi_userinfo";
	}
	
	/** ---------------------------          扩展             ----------------------------*/
	
	/** 
	 *  modify by chan on 2016-09-07
	 *  1.返回值使用ResultObject
	 *  2.使用com.alibaba.fastjson.JSONObject 代替 net.sf.json.JSONObject
	 * 
	 *  log:
	 *  将方法getOpenidByCode ->getUserInfoByAuthorization  2016-09-07
	 */
	/** 通过网页授权获取用户信息 */
	@RequestMapping(value="/getUserInfoByAuthorization")
	@ResponseBody
	public ResultObject getUserInfoByAuthorization(HttpServletRequest request) {

		try {
			/** ---- 解析参数 ---*/
			String code = request.getParameter("code");
			String corpid = request.getParameter("corpid");
			String scope = request.getParameter("scope");		//应用授权作用域
			if (CommonUtil.isNull(code, corpid, scope)) {
				return new ResultObject("100", "参数错误", "");
			}
			
			WechatConfig config = wechatConfigService.getWechatConfigByCorpid(Long.valueOf(corpid));
			if (config == null) {
				return new ResultObject("200", "微信基本设置错误", "");
			}
			
			String appid = config.getWxappid();
			String secret = config.getWxappsecret();
			com.alibaba.fastjson.JSONObject accessToken = wechatConfigService.getAccessToken(appid, secret, code);
			if(accessToken==null){
				return new ResultObject("300", "获取AccessToken出现异常", "");
			}
			if (accessToken.get("errcode") != null) {
				return new ResultObject("400", "获取AccessToken错误,"+accessToken.getString("errmsg"), "");
			}
		
			/** ---- 返回信息 ---*/
			UserInfo userInfo = new UserInfo();
			if(Integer.parseInt(scope)==ScopeEnum.BASE.getValue()){		
				//静默获取
				userInfo.setOpenid(accessToken.getString("openid"));
				return new ResultObject("000", "获取用户信息成功", userInfo);
			}else{
				//授权获取
				String access_token = accessToken.getString("access_token");
				String openid = accessToken.getString("openid");
				com.alibaba.fastjson.JSONObject json = wechatConfigService.getUserInfo(access_token, openid);
				if (json != null && json.get("errcode") != null) {
					return new ResultObject("500", "拉取用户信息错误,"+accessToken.getString("errmsg"), "");
				} else {
					//处理emoji表情
					String nickname = json.getString("nickname");
					nickname = java.net.URLDecoder.decode(nickname,"UTF-8");
					if(CommonUtil.isNotNull(nickname)){
						nickname =EmojiFilter.filterEmoji(nickname);
					}
					userInfo.setOpenid(json.getString("openid"));
					userInfo.setNickname(nickname);									// 昵称
					userInfo.setHeadimgurl(json.getString("headimgurl"));	// 图像
				}
				return new ResultObject("000", "获取用户信息成功", userInfo);
			}
		} catch (Exception e) {
			return new ResultObject("999", "通过网页授权获取用户信息错误", "");
		}
	}
	
	
	
	/** js使用get方式用于跨域的请求
	 *  2015-2-4 add by wayne
	 *  异步获取微信jS-SDK 参数
	 * */
	@SuppressWarnings("finally")
	@RequestMapping(value="/getJsApSign/{corpid}", method = RequestMethod.GET)
	@ResponseBody
	public  Map<String, Object> getJsApSign(HttpServletRequest request,HttpServletResponse response,
			@PathVariable java.lang.Long corpid)throws Exception{
		
		 //允许跨域访问  用于微刊分享方法      
		 response.setHeader("Access-Control-Allow-Origin", "*");
		
		 Map<String, Object> map =  new HashMap<String, Object>();
		 map.put("status", "0");
		 map.put("msg", "提交失败");
		 
		try {
			
			String reurl = request.getParameter("reurl");
			if(CommonUtil.isNull(corpid,reurl)){
				map.put("msg", "参数错误");
				return map;
			}
			
			//获取 wx.config参数 
			Map<String,Object> mapsing=wechatConfigService.getJsApSign(reurl,corpid);
			if(mapsing!=null){
				//mapsing.put("url", url);
//					map.put("jsapi_ticket", mapsing.get("jsapi_ticket"));
//					map.put("nonceStr", mapsing.get("nonceStr"));
//					map.put("timestamp",mapsing.get("timestamp").toString());
//					map.put("signature", mapsing.get("signature"));
				
				map.put("msg", "提交成功");
				map.putAll(mapsing);
				map.put("status", "1");
			}else{
				map.put("status", "-1"); 
				map.put("msg", "生成JS-SDK使用权限签名算法错误");
			 }
			
		} catch (Exception e) {
			map.put("msg", "处理异常");
		}finally{
			return map;
		}
	}
	
//	/** 服务号网页授权获取openid */
//	@RequestMapping(value="/isFocus")
//	@ResponseBody
//	public JSONObject isFocus(HttpServletRequest request) {
//
//		JSONObject result = new JSONObject();
//		try {
//			// 解析参数
//			String corpid = request.getParameter("corpid");
//			String openid = request.getParameter("openid");
//			Long corpId = Long.valueOf(corpid);
//
//			// 获取微信 appid和secret
//			WechatConfig config = wechatConfigService.getWechatConfigByCorpid(corpId);
//			if (config == null) {
//				result.put("errcode", "03");
//				result.put("errmsg", "公众号未设置APPID和APPSECRET!");
//				return result;
//			}
//
//			JSONObject userinfo = wechatConfigService.getUserInfo(openid,corpId);
//			System.out.println("userinfo=="+userinfo);
//			//是否关注的粉丝
//			result.put("isFocus", false);
//			if(userinfo.get("subscribe")!=null && userinfo.get("subscribe").equals(1)){
//				result.put("isFocus", true);
//			}
//	
//			return result;
//		} catch (Exception e) {
//			result.put("errcode", "04");
//			result.put("errmsg", "系统异常 方法：isFocus");
//			return result;
//		}
//		
//	}

	
}
